const app = getApp();
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        role: {
            type: "String",
            value: ""
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        grossWeight: "",
        tareWeight: "",
        carWeight: "",
        netWeight: "0",
        showCropPicker: false,
        showFarmerPicker: false,
        selectCropItem: {},
        selectFarmerItem: {},
        selectQualityItem: {},
        errMessage: {
            carWeight: "请填写皮重",
            cropId: "请选择收货商品",
            cropName: "请选择收货商品",
            farmerUserId: "请选择种植户",
            grossWeight: "请填写毛重",
            qualityType: "请选择商品品质",
        },
        typeList: [],
        farmerList: [],
        cropList: [],
    },
    lifetimes: {
        attached: function () {
            this.getCropList()
            this.getFarmerList()
        },
        detached: function () {
            // 在组件实例被从页面节点树移除时执行
        },
    },

    pageLifetimes: {
        show: function () {
            wx.getStorage({
                key: 'tareWeightType',
                success: (res) => {
                    let typeList = res.data.selectedTypeList
                    let selectQualityItem = res.data.selectQualityItem
                    if (typeList && typeList.length) {
                        let tareWeight = 0
                        typeList.forEach(item => {
                            tareWeight += item.packWeight * 1
                        });
                        this.setData({
                            typeList: typeList,
                            tareWeight: tareWeight
                        })
                    }
                    this.setData({
                        selectQualityItem: selectQualityItem
                    })
                    wx.removeStorage({
                        key: 'tareWeightType',
                    })
                }
            })
        },
    },

    observers: {
        'grossWeight, carWeight, tareWeight': function (grossWeight, carWeight, tareWeight) {
            this.setData({
                netWeight: grossWeight - carWeight - tareWeight
            })
        }
    },

    /**
     * 组件的方法列表
     */
    methods: {
        reset() {
            this.setData({
                grossWeight: "",
                tareWeight: "",
                carWeight: "",
                netWeight: "0",
                showCropPicker: false,
                showFarmerPicker: false,
                typeList:[],
                selectCropItem: {},
                selectFarmerItem: {},
                selectQualityItem: {},
            })
        },
        getCropList() {
            wx.showLoading({
                title: '正在获取商品',
            })
            wx.$apis.getCropList({
                classificationIds: [1, 2, 4]
            }).then(res => {
                res.data.map(item => {
                    item.text = item.cropName
                    return item
                })
                this.setData({
                    cropList: res.data
                })
            })
        },
        getFarmerList() {
            wx.showLoading({
                title: '正在获取农户列表',
            })
            wx.$apis.getMarketUser({
                current: 1,
                size: 1000,
                companyId: app.globalData.userInfo.companyData.companyId,
                marketRoleId: 2
            }).then(res => {
                if (res.data) {
                    res.data.records.map(item => {
                        item.text = `${item.realName}（${item.mobile}）`
                        return item
                    })
                    this.setData({
                        farmerList: res.data.records
                    })
                }
            })
        },
        pickerCrop() {
            this.setData({
                "showCropPicker": true
            })
        },
        onCropConfirm(event) {
            const {
                value
            } = event.detail;
            this.setData({
                selectCropItem: value,
                showCropPicker: false
            })
        },
        onCropCancel() {
            this.setData({
                showCropPicker: false
            })
        },
        pickerFarmer() {
            this.setData({
                showFarmerPicker: true
            })
        },
        onFarmerConfirm(event) {
            const {
                value
            } = event.detail;
            this.setData({
                selectFarmerItem: value,
                showFarmerPicker: false
            })
        },
        onFarmerCancel() {
            this.setData({
                showFarmerPicker: false
            })
        },
        pickerTareWeight() {
            wx.navigateTo({
                url: '/pages/business/tareweight/index',
                success: (res) => {
                    res.eventChannel.emit('acceptDataFromOpenerPage', {
                        typeList: this.data.typeList,
                        selectQualityItem: this.data.selectQualityItem,
                        selectCropItem: this.data.selectCropItem,
                    })
                }
            })
        },
        submit() {
            let params = {
                farmerUserId: this.data.selectFarmerItem.userId || "",
                cropId: this.data.selectCropItem.id || "",
                cropName: this.data.selectCropItem.cropName || "",
                grossWeight: this.data.grossWeight,
                carWeight: this.data.carWeight,
                companyId: app.globalData.userInfo.companyData.companyId,
            }
            for (let key in params) {
                if (!params[key]) {
                    wx.showToast({
                        title: this.data.errMessage[key],
                        icon: 'none',
                        duration: 2000
                    })
                    return
                }
            }
            if (this.data.netWeight < 0) {
                wx.showToast({
                    title: "商品净重小于0，请检查重量是否填写正确",
                    icon: 'none',
                    duration: 2000
                })
                return
            }
            params.qualityType = this.data.selectQualityItem.id || ""
            const {
                typeList,
                role,
                tareWeight
            } = this.data;
            wx.showLoading({
                title: "正在请求数据中"
            })
            if (typeList && typeList.length) {
                params.packs = typeList.map(item => {
                    return {
                        packId: item.packId,
                        packNumber: item.packNumber,
                        packWeight: item.packWeight,
                    }
                })
                params.tareWeight = tareWeight
                wx.$apis.createEnterStock(params).then(res => {
                    if (role == 1) {
                        this.triggerEvent('changeTab', {
                            active: 2
                        })
                    } else {
                        wx.showToast({
                            title: "称重完成，等待交易市场出价！",
                            icon: 'success',
                            duration: 4000
                        })
                        this.reset()
                    }

                })
            } else {
                wx.$apis.createAutoEnterStock(params).then(res => {
                    this.triggerEvent('changeTab', {
                        active: 1
                    })
                })
            }
        },
    }
})